<?php

namespace app\admin\controller;

use app\admin\controller\Base;
use think\Request;
use think\Db;

class Config extends Base
{
    public $add;
    public $check;
    public $del;
    public $update;
    public function __construct()
    {
        parent::__construct();
        $power = $this->checkPower('公司配置');
        if(empty($power)){
            $this->add = 0;
            $this->check =0;
            $this->update =0;
            $this->del =0;
        }else{
            $this->add = $power[0]['padd'];
            $this->check = $power[0]['pcheck'];
            $this->update = $power[0]['pupdate'];
            $this->del = $power[0]['pdel'];
        }
        
    }

    public function index()
    {
        return $this->fetch('list');
    }

    public function newsList()
    {
        //获取每页显示条数
        $limit = Request::instance()->param('limit') ? Request::instance()->param('limit') : 5;
        //获取当前页数
        $page = Request::instance()->param('page') ? Request::instance()->param('page') : 1;
        //计算偏移量
        $offset = ($page - 1) * $limit;

        $list = Db::name('config')->select();
        $count = count($list);
        //查询当前页显示的数据
        $case = Db::name('config')->limit($offset, $limit)->select();
        
        $data = [
            'code' => 0,
            'msg' => '',
            'count' => $count,
            'limit' => $limit,
            'data' => $case,
        ];

        return json($data);
    }

    // 渲染新闻add页面
    public function add()
    {
        return $this->fetch('add');
    }

    //添加或更新
    public function update()
    {
        if($this->update != 1){
            return json(['code' => 3, 'msg' => '您没有这权限！']);
        }

        $data = input('post.data/a');
        $id = input('post.data.cfid/a')[0];
        $table = input('post.table');
        $data = array_filter($data);
      
        $res = Db::name($table)->where('cfid', $id)->update($data);
        if ($res) {
            return json([
                'code' => 0,
                'msg' => '修改成功!',
            ]);
        } else {
            return json([
                'code' => 1,
                'msg' => '修改失败!',
            ]);
        }
    }
}
